/*
 * EmployeesBrowser.java
 *
 * Created on 11 November 2006, 23:33
 *
 * version: 0.2
 *
 */

package org.foment.gem.beans;

import java.awt.Color;
import java.awt.Component;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeModel;
import org.foment.joliage3.sql.Database;

import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import org.foment.joliage3.sql.Table;

/**
 *
 * @author  ivan
 */
public class EmployeesBrowser extends javax.swing.JPanel 
  implements java.io.Serializable, org.foment.joliage3.sql.Table.TableListener {
  
  public class Job {
    public Job(int ID, String Title) {
      _ID = ID;
      _Title = Title;
    }
    
    public int getID() { return _ID; }
    public String getTitle() { return _Title; }
    public String toString() { return _Title; }
    
    private int _ID;
    private String _Title;
  }
  DefaultComboBoxModel _jobs = new DefaultComboBoxModel();
  
  public class Employee {
    public Employee(
      int EmployeeID, String EmployeeFirstName, String EmployeeSurname,
      /*int JobTypeID,*/ String JobTypeTitle /*,
      int JobID, String JobTitle*/
    ) {
      _EmployeeID = EmployeeID;
      //_JobTypeID = JobTypeID;
      //_JobID = JobID;
      
      _EmployeeFirstName = (EmployeeFirstName != null) ? EmployeeFirstName : "";
      _EmployeeSurname =   (EmployeeSurname   != null) ? EmployeeSurname   : "";
      _JobTypeTitle =      (JobTypeTitle      != null) ? JobTypeTitle      : i18n("Undefined");
      //_JobTitle =          (JobTitle          != null) ? JobTitle          : i18n("Undefined");
    }
      
    private int _EmployeeID, _JobTypeID, _JobID;
    private String _EmployeeFirstName, _EmployeeSurname;
    private String _JobTypeTitle, _JobTitle;
      
    public int getEmployeeID() { return _EmployeeID; }
    public int getJobTypeID() { return _JobTypeID; }
    public int getJobID() { return _JobID; }

    public String getEmployeeFirstName() { return _EmployeeFirstName; }
    public String getEmployeeSurname() { return _EmployeeSurname; }
    public String getJobTypeTitle() { return _JobTypeTitle; }
    public String getJobTitle() { return _JobTitle; }
      
    public String toString() {
      return _EmployeeSurname + ", " + _EmployeeFirstName + "\n" + _JobTypeTitle;
    }
  }
  private DefaultListModel _employes = new DefaultListModel();
  
  public void loadJobs() throws SQLException {
    _jobs.removeAllElements();
    
    Database.getTable("Job").pushState();
    
    ResultSet rs = Database.getTable("Job").getResultSet();
    
    rs.beforeFirst();
    _jobs.addElement(new Job(-1, i18n("All")));
    _jobs.addElement(new Job(-2, i18n("Uncategorized")));
    while (rs.next()) {
      _jobs.addElement(new Job(rs.getInt("JobID"), rs.getString("JobTitle")));
    }
    
    Database.getTable("Job").popState();
    
    cmbCategory.setModel(_jobs);
  }
  
  public void loadEmployees() throws SQLException {
    Job job = ((Job)cmbCategory.getSelectedItem());
    if (job == null)
      loadEmployees(-1);
    else
      loadEmployees(job.getID());
  }
  
  public void loadEmployees(int JobID) throws SQLException {
    _employes.clear();
    String WhereJobID = "";
    if (JobID == -1) {
      // Nothing
    } else if (JobID == -2) {
      WhereJobID = "WHERE J.JobID IS NULL ";
    } else {
      WhereJobID = "WHERE J.JobID = '" + String.valueOf(JobID) + "' ";
    }
    
    String query = 
      "SELECT E.EmployeeID, E.EmployeeFirstName, E.EmployeeSurname, " +
      "GROUP_CONCAT(JT.JobTypeTitle SEPARATOR ', ') as JobTypeTitles " +
      "FROM Employee E " +
      "LEFT OUTER JOIN EmployeeJobType EJT ON EJT.EmployeeID = E.EmployeeID AND EJT.EmployeeJobTypeActive = '1' " +
      "LEFT OUTER JOIN JobType JT ON EJT.JobTypeID = JT.JobTypeID " +
      "LEFT OUTER JOIN Job J ON JT.JobID = J.JobID " +
      WhereJobID +
      "GROUP BY E.EmployeeID " +
      "ORDER BY J.JobTitle, JT.JobTypeTitle, E.EmployeeSurname, E.EmployeeFirstName;";
    Connection conn = Database.getConnection();
    ResultSet rs = conn.createStatement().executeQuery(query);
    while (rs.next()) {
      _employes.addElement(
        new Employee(
          rs.getInt("EmployeeID"), rs.getString("EmployeeFirstName"), rs.getString("EmployeeSurname"),
          /*rs.getInt("JobTypeID"),*/ rs.getString("JobTypeTitles") /*,
          rs.getInt("JobID"), rs.getString("JobTitle")*/
        )        
      );
    }
    rs.close();
    conn.close();
    listEmployees.setModel(_employes);
    
    
  }
  
  public class EmployeeRenderer extends javax.swing.JTextPane implements ListCellRenderer {
    
 
    public EmployeeRenderer() {
      setBorder(new javax.swing.border.EmptyBorder(6, 6, 6, 6));
      //setDocument(html = new javax.swing.text.html.HTMLDocument());
      setContentType("text/html");
      setFont(new java.awt.Font("Dialog", 0, 12));
    }
    
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      Employee employee = (Employee)value;
      String text = "<html><body><table width='170'><tr><td>" +
        "<font face=\"sans\" size=\"3\"><b>" + employee.getEmployeeSurname() + ", " + employee.getEmployeeFirstName() + "</b></font><br>" +
        "<font face=\"sans\" size=\"2\">" + employee.getJobTypeTitle() + "</font></td></tr></table></body></html>";
      setText(text);
      //setSize(100, 200);
      
      
      if (isSelected) {
        setBackground(new Color(157, 183, 212));
      } else {
        if (index % 2 == 0)
          setBackground(new Color(255, 255, 255));
        else
          setBackground(new Color(238, 246, 255));
      }
      
      return this;
    }
  }

  
  /**
   * Creates new form EmployeesBrowser
   */
  public EmployeesBrowser() {
    initComponents();
    listEmployees.setCellRenderer(new EmployeeRenderer());
    try {
      loadJobs();
      loadEmployees();
      Database.getTable("Employee").addListener(this);
      Database.getTable("EmployeeJobType").addListener(this);
      Database.getTable("JobType").addListener(this);
      Database.getTable("Job").addListener(this);
      //Database.getTable("EmployeeInsurance").addListener(this);
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
    
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  private void initComponents() {
    scrollEmployees = new javax.swing.JScrollPane();
    listEmployees = new javax.swing.JList();
    cmbCategory = new javax.swing.JComboBox();
    lblJobs = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();

    listEmployees.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
      public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
        listEmployeesValueChanged(evt);
      }
    });
    listEmployees.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        listEmployeesMouseClicked(evt);
      }
    });

    scrollEmployees.setViewportView(listEmployees);

    cmbCategory.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cmbCategoryActionPerformed(evt);
      }
    });

    lblJobs.setText(i18n("Main Job Position"));

    jLabel1.setText(i18n("Employees"));

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(cmbCategory, 0, 424, Short.MAX_VALUE)
      .add(scrollEmployees, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
      .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
      .add(org.jdesktop.layout.GroupLayout.TRAILING, lblJobs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(layout.createSequentialGroup()
        .add(lblJobs)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(cmbCategory, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(jLabel1)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(scrollEmployees, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void listEmployeesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listEmployeesMouseClicked
    Employee employee = (Employee)listEmployees.getSelectedValue();
    if (employee == null) {
      setSelectedEmployeeID(-1);
    } else {
      setSelectedEmployeeID(employee.getEmployeeID());
    }
    listEmployees.clearSelection();
  }//GEN-LAST:event_listEmployeesMouseClicked

  private void listEmployeesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listEmployeesValueChanged
    /*if (!evt.getValueIsAdjusting()) {
      Employee employee = (Employee)listEmployees.getSelectedValue();
      if (employee == null) {
        setSelectedEmployeeID(-1);
      } else
        setSelectedEmployeeID(employee.getEmployeeID());
    }*/
    //listEmployees.clearSelection();
  }//GEN-LAST:event_listEmployeesValueChanged

  private void cmbCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCategoryActionPerformed
    if (evt.getActionCommand().equals("comboBoxChanged")) {
      try {
        loadEmployees();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
    }
  }//GEN-LAST:event_cmbCategoryActionPerformed
 
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JComboBox cmbCategory;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel lblJobs;
  private javax.swing.JList listEmployees;
  private javax.swing.JScrollPane scrollEmployees;
  // End of variables declaration//GEN-END:variables

  /**
   * Holds value of property selectedEmployeeID.
   */
  private int _selectedEmployeeID = -1;

  /**
   * Utility field used by bound properties.
   */
  private java.beans.PropertyChangeSupport _propertyChangeSupport =  new java.beans.PropertyChangeSupport(this);

  /**
   * Adds a PropertyChangeListener to the listener list.
   * @param l The listener to add.
   */
  public void addPropertyChangeListener(java.beans.PropertyChangeListener l) {
    _propertyChangeSupport.addPropertyChangeListener(l);
  }

  /**
   * Removes a PropertyChangeListener from the listener list.
   * @param l The listener to remove.
   */
  public void removePropertyChangeListener(java.beans.PropertyChangeListener l) {
    _propertyChangeSupport.removePropertyChangeListener(l);
  }

  /**
   * Getter for property selectedEmployeeID.
   * @return Value of property selectedEmployeeID.
   */
  public int getSelectedEmployeeID() {
    return _selectedEmployeeID;
  }

  /**
   * Setter for property selectedEmployeeID.
   * @param selectedEmployeeID New value of property selectedEmployeeID.
   */
  public void setSelectedEmployeeID(int selectedEmployeeID) {
    int oldSelectedEmployeeID = _selectedEmployeeID;
    _selectedEmployeeID = selectedEmployeeID;
    _propertyChangeSupport.firePropertyChange ("selectedEmployeeID", new Integer (oldSelectedEmployeeID), new Integer (selectedEmployeeID));
  }

  public void tableRowDeleted(Table table, int row) {
    tableDataChanged(table);
  }

  public void tableRowUpdated(Table table, int row) {
    tableDataChanged(table);
  }

  public void tableRowInserted(Table table) {
    tableDataChanged(table);
  }

  public void tableDataChanged(Table table) {
    try {
      if (table.getTableName().equals("Job"))
        loadJobs();
      loadEmployees();
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }
  
}
